package com.vhr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vhr.VO.EmpVO;
import com.vhr.VO.LeaderVO;
import com.vhr.VO.TrainVO;
import com.vhr.entities.Employee;
import com.vhr.entities.Result;
import com.vhr.entities.Train;
import com.vhr.form.TrainForm;
import com.vhr.service.IEmployeeService;
import com.vhr.service.ITrainService;
import com.vhr.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "培训模块")
@CrossOrigin(allowCredentials="true",allowedHeaders="*")
public class TrainController {


    @Autowired
    private ITrainService trainService;

    @Autowired
    private IEmployeeService employeeService;

    /*统一：根据员工查询培训班:访问：http://localhost:8080/train/findByEmployee */
    @ApiOperation("统一：根据员工查询培训班")
    @GetMapping("/train/findByEmployee")
    public Result findByEmployee(@RequestParam("id")Integer id,
                                 @RequestParam(value = "pageNum")int pageNum){
        Employee employee = new Employee();
        employee.setEmpId(id);

       // PageHelper.startPage(pageNum,5);
        Page page = PageHelper.startPage(pageNum,10);
        List<TrainVO> results = trainService.selectByEmployee(employee);
        PageInfo<TrainVO> pageInfo = new PageInfo<TrainVO>(page);
        pageInfo.setList(results);

        //System.out.println("pageInfo:"+pageInfo.getTotal());
        if(pageInfo!=null){
            return Result.success().add("trainList",pageInfo);
        }else {
            return Result.fail("结果为空");
        }
    }

    /*管理员：显示所有培训班*/
    @ApiOperation("管理员：显示所有培训班")
    @GetMapping("/api/train/findAll")
    public Result findAll(@RequestParam(value = "pageNum")int pageNum){

        Page page = PageHelper.startPage(pageNum,10);
        List<TrainVO> results = trainService.selectAll();
        PageInfo<TrainVO> pageInfo = new PageInfo<TrainVO>(page);
        pageInfo.setList(results);
        if(pageInfo!=null){
            return Result.success().add("trainList",pageInfo);
        }else {
            return Result.fail("结果为空");
        }

    }

    /*管理员：根据培训班主键查询该班级员工:访问：http://localhost:8080/train/findByPrimaryKey */
    @ApiOperation("管理员：根据培训班主键查询该班级员工")
    @GetMapping("/api/train/findByPrimaryKey")
    public Result findEmployeeByPrimaryKey(@RequestParam("id")Integer id,
                                   @RequestParam(value = "pageNum",defaultValue = "1") int pageNum){
        Train train = new Train();
        train.setTrainId(id);

        Page page = PageHelper.startPage(pageNum,10);
        List<Employee> employeeList= trainService.selectByPrimaryKey(train);

        PageInfo<Employee> pageInfo = new PageInfo<Employee>(page);
        pageInfo.setList(employeeList);

        if(pageInfo!=null){
            return Result.success().add("empList",pageInfo);
        }else {
            return Result.fail("结果为空");
        }
    }

    /*管理员:根据主键查找培训课程*/
    @ApiOperation("管理员:根据主键查找培训课程")
    @GetMapping("/api/train/selectbyPrimaryKey")
    public Result selectbyPrimaryKey(@RequestParam("trainId")Integer trainId){
        TrainForm train = trainService.selectByPrimary(trainId);
        if(train!=null){
            return Result.success().add("train",train);
        }else {
            return Result.fail();
        }
    }

    /*管理员：根据培训班其他条件查询(培训人数、培训开始时间、培训班名称):访问：http://localhost:8080/train/findByOtherCondition */
    @ApiOperation("管理员：根据培训班其他条件查询(trainTime(开始时间),trainContent)")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "trainContent",required = false,value = "培训内容名",dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "trainTime",required = false,value = "培训时间",dataType = "String"),
            @ApiImplicitParam(paramType = "query",name="pageNum",required = false,value = "第几页",defaultValue = "1",dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name="pageSize",required = false,value = "一页有几条数据",defaultValue = "10",dataType = "Integer")
    })
    @GetMapping("/api/train/findByOtherCondition")
    public Result findByOtherCondition(Train train, @RequestParam(value = "pageNum")int pageNum, @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){

        String trainTime = null;
        String trainContent=null;
        if(train.getTrainTime()!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            trainTime = sdf.format(train.getTrainTime());
        }
        if(train.getTrainContent()!=null){
            trainContent = train.getTrainContent();
        }
        Page page = PageHelper.startPage(pageNum,pageSize);

        List<TrainVO> results = trainService.selectByContentOrTime(trainContent,trainTime);
        PageInfo<TrainVO> pageInfo = new PageInfo<TrainVO>(page);
        pageInfo.setList(results);
        if(pageInfo!=null){
            return Result.success().add("trainList",pageInfo);
        }else {
            return Result.fail("结果为空");
        }
    }

    /*管理员：插入培训班:访问：http://localhost:8080/train/insertTrain */

    @ApiOperation("管理员：插入培训班")
    @PostMapping("/api/train/insertTrain")
    public Result  insertTrain(@RequestBody TrainForm trainForm){
        int result = trainService.insertTrain(trainForm);
        if(result!=0){
                return Result.success();
        }else {
            return Result.fail("插入失败");
        }
    }


    /*管理员：根据培训班主键更新培训班:访问：http://localhost:8080/train/updateTrain */
    @ApiOperation("管理员：根据培训班主键更新培训班")
    @PutMapping("/api/train/updateTrain")
    public Result updateTrain(@RequestBody TrainForm trainForm){
        int result = trainService.changeLeaderIdByEmpName(trainForm);
        if(result!=0){
            return Result.success();
        }else {
            return Result.fail("更新失败");
        }
    }

    /*管理员：获取十个负责人名字及id*/
    @ApiOperation("管理员：获取十个负责人名字及id")
    @GetMapping("/api/train/getLeaders")
    public Result getLeaders(){
        List<LeaderVO> leaderVOS = trainService.getLeaders();
        if(leaderVOS !=null){
            return Result.success().add("leaders", leaderVOS);
        }else {
            return Result.fail("查询失败");
        }
    }

    /*管理员删除培训课程*/
    @ApiOperation("管理员删除培训课程")
    @DeleteMapping("/api/train/deleteTrain")
    public Result deleteTrain(@RequestParam(value = "trainId",required = false)Integer trainId){
        int result=0;
        if(trainId!=null){
            result = trainService.deleteTrain(trainId);
        }
        if(result!=0){
            return Result.success();
        }else {
            return Result.fail("删除失败");
        }

    }

    /*管理员：往培训班里添加员工:访问：http://localhost:8080/train/insertToTrainEmp */
    @ApiOperation("管理员往培训班里添加员工")
    @PostMapping("/api/train/insertToTrainEmp")
    public Result insertToTrainEmp(@RequestParam(value = "empId") List<Integer> empId,@RequestParam(value ="trainId" ) Integer trainId){
        int result = trainService.insertEmployee(empId,trainId);
        if(result!=0){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    /*管理员：删除培训班里的员工：访问：http://localhost:8080/train/deleteToTrainEmp */
    @ApiOperation("管理员：删除培训班里的员工")
    @DeleteMapping("/api/train/deleteToTrainEmp")
    public Result deleteToTrainEmp(@RequestParam(value = "empId")List<Integer> empId,@RequestParam(value = "trainId") Integer trainId){
        int result = trainService.deleteEmployee(empId,trainId);
        if(result!=0){
            return Result.success();
        }else{
            return Result.fail();
        }
    }

    /*管理员：返回所有员工（id,员工名,状态码,0在课程，1不在）*/
    @ApiOperation("管理员：返回所有员工（id,员工名,状态码,0在课程，1不在）")
    @GetMapping("/api/train/listAllEmpByStatus")
    public Result listAllEmpByStatus(@RequestParam(value = "trainId")Integer trainId){
        List<EmpVO> empVOList =trainService.listAllEmpByStatus(trainId);
        if(empVOList !=null){
            return Result.success().add("empList", empVOList);
        }else {
            return Result.fail("结果为空");
        }
    }

    /*管理员：编辑培训课程内员工*/
    @ApiOperation(("管理员：编辑培训课程内员工,添加、删除"))
    @PutMapping("/api/train/editTrainEmp")
    @ResponseBody
    public Result editTrainEmp(@RequestBody HashMap<String,String> map){

/*        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.print(entry.getKey());
            System.out.println(entry.getValue());
        }*/
        JSONArray empId = JSON.parseArray(map.get("empId"));
        List<Integer> empList = JSONObject.parseArray(empId.toJSONString(),Integer.class);

        Integer trainId = Integer.parseInt(map.get("trainId"));

        int result = trainService.editTrainEmp(empList,trainId);
        if(result!=0){
            return Result.success();
        }else {
            return Result.fail("编辑失败");
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
    }

}